package fmt

import (
	"fmt"
	"strings"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnSprintfArray{})
	if err != nil {
		panic(err)
	}
}

type fnSprintfArray struct {
}

func (fnSprintfArray) Name() string {
	return "sprintfArray"
}

func (fnSprintfArray) Sig() (paramsTypes []data.Type, isVariadic bool) {
	return []data.Type{
		data.TypeString, // element format
		data.TypeString, // separator
		data.TypeString, // head
		data.TypeString, // tail
		data.TypeArray,  // payload
	}, false
}

func (fnSprintfArray) Eval(params ...interface{}) (interface{}, error) {
	if len(params) != 5 {
		return nil, fmt.Errorf("expect 5 argument, got %d", len(params))
	}
	format, err := coerce.ToString(params[0])
	if err != nil {
		return nil, err
	}
	separator, err := coerce.ToString(params[1])
	if err != nil {
		return nil, err
	}
	head, err := coerce.ToString(params[2])
	if err != nil {
		return nil, err
	}
	tail, err := coerce.ToString(params[3])
	if err != nil {
		return nil, err
	}
	payload, err := coerce.ToArray(params[4])
	if err != nil {
		return nil, err
	}
	ss := make([]string, len(payload))
	for idx, item := range payload {
		s := fmt.Sprintf(format, item)
		ss[idx] = s
	}
	res := fmt.Sprintf("%s%s%s", head, strings.Join(ss, separator), tail)
	return res, nil
}
